package com.angel.web.app;

import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.angel.core.Constants;
import com.angel.core.base.JsonEntity;
import com.angel.core.util.CodeUtil;
import com.angel.core.util.FileUpload;
import com.angel.core.util.JsonUtil;
import com.angel.core.util.MD5Util;
import com.angel.core.util.SMSUtils;
import com.angel.health.BuzCustomer;
import com.angel.health.BuzCustomerLog;
import com.angel.health.SMS;
import com.angel.health.SysSendMessage;
import com.angel.health.ln.WangYi;
import com.angel.provider.app.WangYiProvider;
import com.angel.provider.health.BuzCustomerLogProvider;
import com.angel.provider.health.BuzCustomerProvider;
import com.angel.provider.sys.SysSendMessageProvider;

/**
 * 客户信息管理
 * 
 * @author cheng sir
 *
 */
@Controller
@RequestMapping("app/cus")
public class AppCustomerController {

	@Autowired
	private BuzCustomerProvider customerProvider;
	@Autowired
	private WangYiProvider wyService;
	@Autowired
	private SysSendMessageProvider sysSendMessageProvider;
	@Autowired
	private BuzCustomerLogProvider bclProvider;
	/**
	 * 用户登录
	 */
	@ResponseBody
	@RequestMapping(value = "login", produces = "application/json; charset=utf-8")
	public String login(@ModelAttribute("buzCustomer") BuzCustomer buzCustomer) {
		buzCustomer.setEnable(1);
		buzCustomer.setPassword(MD5Util.getMD5(buzCustomer.getPassword()));
		List<Map<String, Object>> list = customerProvider.findCustomerList(buzCustomer);
		if (list != null && list.size() > 0) {
			return JsonUtil.toJson(new JsonEntity("200", list.get(0)));
		}
		return JsonUtil.toJson(new JsonEntity("-1", "帐号密码不正确！"));
	}

	/**
	 * 注册
	 * 
	 * @param request
	 * @param buzCustomer
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "addCustomer", produces = "application/json; charset=utf-8")
	public String addCustomer(HttpServletRequest request, @ModelAttribute("buzCustomer") BuzCustomer buzCustomer) {
		if (StringUtils.isEmpty(buzCustomer.getMemPhone())) {
			return JsonUtil.toJson(new JsonEntity("-1", "参数不正确！"));
		}
		// 去云信注册
		String createUser;
		try {
			createUser = wyService.createUser(JsonUtil.toJson(new WangYi(buzCustomer.getMemPhone(),buzCustomer.getName())));
			if (!StringUtils.isEmpty(createUser)) {
				Map<String, String> map = JsonUtil.jsonStringToMap(createUser);
				if ("200".equals(map.get("code"))) {
					buzCustomer.setToken(map.get("token"));
					buzCustomer.setStatus(1);
					List<Map<String, Object>> customerCount = customerProvider.findCustomerByPhone(buzCustomer);
					if (customerCount.size() > 0) {
						return JsonUtil.toJson(new JsonEntity("0", "已存在"));
					}
					buzCustomer.setLabelId(1);
					buzCustomer.setPassword(MD5Util.getMD5(buzCustomer.getPassword()));
					buzCustomer.setLevelId(1);
					int save = customerProvider.insert(buzCustomer);
					
					//更新客户编码
					buzCustomer.setCode(CodeUtil.createCode(null, Constants.CUSTOMERNUM, buzCustomer.getId()));
					customerProvider.updateById(buzCustomer);
					//增加客户日志
					BuzCustomerLog bcl = new BuzCustomerLog();
					bcl.setContent("您注册成功！");
					bcl.setCustomerId(buzCustomer.getId());
					bcl.setType(1);
					bclProvider.insert(bcl);
					if (save == 0) {
						return JsonUtil.toJson(new JsonEntity("-1", "注册失败"));
					} else {
						return JsonUtil.toJson(new JsonEntity("200", "注册成功"));
					}
				}
			}
		} catch (Exception e) {
			return JsonUtil.toJson(new JsonEntity("-1", "注册失败"));
		}
		return JsonUtil.toJson(new JsonEntity("-1", "注册失败"));

	}

	/**
	 * 完善信息
	 */
	@ResponseBody
	@RequestMapping(value = "edit", produces = "application/json; charset=utf-8")
	public String editCustomer(@ModelAttribute("buzCustomer") BuzCustomer buzCustomer,HttpServletRequest req
			) {
		if(buzCustomer.getId() == null){
			return JsonUtil.toJson(new JsonEntity("-1", "参数不正确"));
		}
		try {
			MultipartHttpServletRequest request = (MultipartHttpServletRequest) req;
			MultiValueMap<String, MultipartFile> multiFileMap = request.getMultiFileMap();
			String uploadUrl;
			uploadUrl = FileUpload.uploadForFastdfs(multiFileMap);
			buzCustomer.setPortraitUrl(uploadUrl);
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
//			return JsonUtil.toJson(new JsonEntity("-1", "失败"));
		}
		int updateById = customerProvider.updateById(buzCustomer);
		if (updateById > 0) {
			buzCustomer = customerProvider.findById(buzCustomer);
			try {
				String updateUinfo = wyService.updateUinfo(JsonUtil.toJson(buzCustomer));
			} catch (Exception e) {
				// TODO Auto-generated catch block
				
			}
			return JsonUtil.toJson(new JsonEntity("200", buzCustomer));
		}
		return JsonUtil.toJson(new JsonEntity("-1", "修改失败"));
	}

	/**
	 * 根据旧密码修改密码
	 */
	@ResponseBody
	@RequestMapping(value = "upfop", produces = "application/json; charset=utf-8")
	public String updatePwordForOldPword(@ModelAttribute("buzCustomer") BuzCustomer buzCustomer) {
		if (StringUtils.isEmpty(buzCustomer.getOldPassword())) {
			return JsonUtil.toJson(new JsonEntity("-1", "旧密码不正确"));
		}
		BuzCustomer bc = new BuzCustomer();
		bc.setMemPhone(buzCustomer.getMemPhone());
		bc.setPassword(MD5Util.getMD5(buzCustomer.getOldPassword()));
		List<Map<String, Object>> list = customerProvider.findCustomerList(bc);
		if (list.size() > 0) {
			buzCustomer.setId(Integer.parseInt(list.get(0).get("id").toString()));
			buzCustomer.setPassword(MD5Util.getMD5(buzCustomer.getPassword()));
			int updateById = customerProvider.updateById(buzCustomer);
			if (updateById > 0) {
				return JsonUtil.toJson(new JsonEntity("200", "修改成功"));
			}
		}
		return JsonUtil.toJson(new JsonEntity("-1", "旧密码不正确"));
	}
	
	/**
	 * 忘记密码
	 * @param buzCustomer
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="iforgot",produces = "application/json; charset=utf-8")
	public String iforgot(@ModelAttribute("buzCustomer") BuzCustomer buzCustomer){
		if(StringUtils.isEmpty(buzCustomer.getPassword())){
			return JsonUtil.toJson(new JsonEntity("-1","请输入正确的密码！"));
		}
		List<Map<String, Object>> list = customerProvider.findCustomerByPhone(buzCustomer);
		if(list.size() > 0){
			buzCustomer.setId(Integer.parseInt(list.get(0).get("id").toString()));
			buzCustomer.setPassword(MD5Util.getMD5(buzCustomer.getPassword()));
			int updateById = customerProvider.updateById(buzCustomer);
			if (updateById > 0) {
				return JsonUtil.toJson(new JsonEntity("200", "修改成功"));
			}
		}
		return JsonUtil.toJson(new JsonEntity("-1","不存在的手机号码！"));
	}
	
	/**
	 * 
	 * @param memPhone
	 * @param 获取验证码
	 * 		type  1.注册 2.找回密码
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="getCode", produces = "application/json; charset=utf-8")
	public String getCode(String memPhone,String type){
		if(StringUtils.isEmpty(memPhone)){
			return JsonUtil.toJson(new JsonEntity("-1","手机号不存在！"));
		}
		String content = "为您在天使健康的找回密码验证码【天使健康】";
		BuzCustomer buzCustomer = new BuzCustomer();
		buzCustomer.setMemPhone(memPhone);
		List<Map<String,Object>> list = customerProvider.findAll(buzCustomer);
		if("1".equals(type)){
			content = "为您在天使健康的注册验证码【天使健康】";
			if(list.size() > 0){
				return JsonUtil.toJson(new JsonEntity("-1","已注册"));
			}
		}else{
			if(list.size() == 0){
				return JsonUtil.toJson(new JsonEntity("-1","未注册"));
			}
		}
		String code = "";
		Random random = new Random();
		for(int i = 0;i<4;i++){
			int nextInt = random.nextInt(10);
			code += nextInt;
		}
		content = code+content;
		SysSendMessage sysSendMessage = new SysSendMessage(1,memPhone,content,null);
		int insert = sysSendMessageProvider.insert(sysSendMessage);
		if(insert > 0){
			String single = Constants.SEND_SMS_SINGLE;
			JsonEntity json = SMSUtils.send(new SMS(sysSendMessage.getId().toString(),memPhone,content,sysSendMessage.getId().toString(),""),single);
			if("200".equals(json.getCode())){
				return JsonUtil.toJson(new JsonEntity("200",code));
			}
			return JsonUtil.toJson(json);
		}
		return JsonUtil.toJson(new JsonEntity("-1","发送失败！"));
	}
	
	/**
	 * 查看用户操作记录
	 * @param customerId
	 * @param type
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/log/{customerId}/{type}", produces = "application/json; charset=utf-8")
	public String log(@PathVariable("customerId") Integer customerId,@PathVariable("type") Integer type){
		if(customerId == null){
			return JsonUtil.toJson(new JsonEntity("-1","参数错误！"));
		}
		type = (type == -1?null:type);
		BuzCustomerLog bcl = new BuzCustomerLog(customerId, type);
		List<Map<String, Object>> list = bclProvider.findAll(bcl);
		return JsonUtil.toJson(new JsonEntity("200",list));
	}
}
